package com.zking.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zking.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by OWen on 2023-2023/11/24, project: springboot1206.
 * <p>
 * Author: OWen
 * Create Date: 2023/11/24
 * Project: com.zking.service in project: springboot1206
 * <p>
 * Notice: If you are using this class or file, check it and do some modification.
 */
@RequiredArgsConstructor @Slf4j
public class UserService {
    private final JedisPool jedisPool;
    
    public User findById(int id) {
        try(Jedis jedis = jedisPool.getResource()) {
            // 从Redis中去获取
            String key = "user::" + id;
            boolean exists = jedis.exists(key);
            if (exists) {
                // 存在
                String json = jedis.get(key);
                User user = new ObjectMapper().readValue(json, User.class);
                log.debug("存在这个用户：{}", json);
                return user;
            } else {
                // 不存在：从数据库中获取数据
                // User user = IUserMapper.selectById(id);
                User user = new User();
                user.setId(id);
                user.setUsername("test" + ThreadLocalRandom.current().nextInt(1000));
                user.setPassword("123");
                user.setMoney(0.0);
                log.debug("不存在这个 ID={} 的用户，从数据库中获取：{}", id, user);
                // 保存到Redis缓存，然后再返回
                String json = new ObjectMapper().writeValueAsString(user);
                jedis.set(key, json);
                log.debug("保存用户到了Redis，下次直接获取！id={}", id);
                // 不要直接返回
                return user;
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    
    public User updateById(int id) {
        // 更新数据库：UserService + IUserMapper
        // 立刻将Redis中缓存删除！
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.del("user::" + id);
        }
        return null;
    }
}
